import React, { useRef } from 'react'
import { Modal, Button, Input } from 'antd';
import styles from '../../styles/home/modalShow.scss'
import axios from 'axios'
import { getToken, commonReply } from '../common/util';
import { backIP, axiosConfig, error } from '../common/config';

export default function HouseModalShow({ setFloorNumber, setName, visible, setVisivble, loading, setLoading, house_id, type, name, floorNumber, clear, getHouseInfo }) {
    const nameRef = useRef();
    const floorRef = useRef();

    const handleOk = async () => {
        const changedName = (nameRef.current as any).state.value
        const changedFloorNumber = (floorRef.current as any).state.value
        if (!(changedName && changedFloorNumber)) {
            error('请求参数不能为空')
            return
        }
        setLoading(true)
        const token: string = getToken()

        const sendData = type === 'modify' ? {
            house_id: parseInt(house_id),
            name: changedName,
            floor_number: parseInt(changedFloorNumber)
        } : {
                name: changedName,
                floor_number: parseInt(changedFloorNumber)
            }
        const { data: res }: { data: axiosConfig } = await axios({
            url: `${backIP}/house/${type}`,
            data: sendData,
            method: 'post',
            headers: { Authorization: token }
        });
        res.code === 0 && getHouseInfo(token)
        commonReply(res)
        setLoading(false)
        clear()
        setVisivble(false)
    };
    const handleCancel = () => {
        setVisivble(false)
        clear()
    };

    return (
        <Modal
            visible={visible}
            title={type === 'modify' ? '修改' : '增加'}
            onOk={handleOk}
            onCancel={handleCancel}
            footer={[
                <Button key="back" onClick={handleCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                    提交
                </Button>,
            ]}
        >
            <Input placeholder="名称" value={name} className={styles.input} ref={nameRef} onChange={(e) => setName(e.target.value)} />
            <Input placeholder="楼层数" value={floorNumber} className={styles.input} ref={floorRef} onChange={(e) => setFloorNumber(e.target.value)} />
        </Modal>
    )
}
